package com.demo.java.spring.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.Query;
import java.util.List;

@Repository
public class CatalogDao {

    @Autowired
    private EntityManager em;


    public void update(Catalog catalog) {
        em.merge(catalog);
    }

    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    public Catalog findById(int id) {
        Query query = em.createQuery("from Catalog where id=:id");
        query.setParameter("id", id);
        List<Catalog> list = query.getResultList();
        return list.size() > 0 ? list.get(0) : null;
    }

    // 悲观锁
    public Catalog findByIdForUpdateSql(int id) {
        Query query = em.createNativeQuery("select * from catalog where id=:id for update", Catalog.class);
        query.setParameter("id", id);
        List<Catalog> list = query.getResultList();
        return list.size() > 0 ? list.get(0) : null;
    }
}
